import React, { useState, useEffect } from 'react';
import { List, ImagePicker, Toast, InputItem, Button, NavBar, Icon } from 'antd-mobile'
import { createForm } from 'rc-form'
import { useStoreHook } from 'think-react-store'
import { history } from 'umi'

function Edit(props) {
  const { getFieldProps, validateFields } = props.form
  const { user: { editUserAsync, getUserAsync, avatar, phone, sign } } = useStoreHook();
  const [files, setFiles] = useState([{ url: avatar }])

  const handleChange = (files) => {
    // console.log(files)
    if (files[0]?.file?.size / 1024 / 1024 > 1) {
      Toast.fail('文件过大')
      return;
    }
    setFiles(files)
  }

  const handleSubmit = () => {
    if (!files.length) {
      Toast.fail('请上传图片')
    }
    validateFields((error, value) => {
      // console.log(err)
      if (error) {
        Toast.fail('请填写完整信息')
        return;
      } else {
        editUserAsync({
          avatar: files[0].url,
          phone: value.tel,
          sign: value.sign
        });
      }
    })
  }

  useEffect(() => {
    // console.log(props)
    getUserAsync({})
  }, [])

  return (
    <div>
      <NavBar
        mode="dark"
        icon={<Icon type="left" />}
        onLeftClick={() => history.push('/user')}
      >修改信息</NavBar>
      <div className='user-edit'>
        <List>
          <List.Item>
            <ImagePicker
              files={files}
              selectable={files.length < 1}
              onChange={handleChange}
            />
          </List.Item>
          <List.Item>
            <InputItem
              {...getFieldProps('tel', {
                rules: [{ required: true }],
                initialValue: phone
              })}
              placeholder='电话'
            >
              电话：
          </InputItem>
          </List.Item>
          <List.Item>
            <InputItem
              {...getFieldProps('sign', {
                rules: [{ required: true }],
                initialValue: sign
              })}
              placeholder='签名'
            >
              签名：
          </InputItem>
          </List.Item>
        </List>
        <Button type='warning' style={{ marginTop: '20px' }} onClick={handleSubmit}>修改</Button>
      </div>
    </div>
  )
}

export default createForm()(Edit);